package requests

import (
	"beego/comm/utils"
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/astaxie/beego"
)

func Post(url string, data interface{}, param_i ...map[string]interface{}) (result string) {
	beego.Info("================= Post start =================")
	defer func() {
		err := recover()
		if nil != err {
			beego.Info("请求出现异常: ", err)
			errorInfo := map[string]interface{}{
				"error": err,
			}
			e_result, _ := json.Marshal(errorInfo)
			result = string(e_result)
			return
		}
	}()
	jsonStr, err := json.Marshal(data)
	beego.Info("请求体: ", string(jsonStr))
	if nil != err {
		panic("json错误: " + err.Error())
	}
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	defer req.Body.Close()
	param := map[string]interface{}{}
	if len(param_i) > 0 {
		param = param_i[0]
	}
	auth_i := utils.GetDefault(param, "auth", nil)
	if nil != auth_i {
		auth := auth_i.(map[string]string)
		beego.Info("auth: ", auth)
		req.SetBasicAuth(auth["username"], auth["password"])
	}
	if nil != err {
		panic("post连接错误: " + err.Error())
	}
	contentType := utils.GetDefault(param, "contentType", "application/json").(string)
	beego.Info("contentType: ", contentType)
	req.Header.Add("content-type", contentType)
	timeout := utils.GetDefault(param, "timeout", 5).(int)
	client := &http.Client{Timeout: time.Second * time.Duration(timeout)}
	resp, err := client.Do(req)
	if nil != err {
		panic("post请求错误: " + err.Error())
	}
	defer resp.Body.Close()
	resp_data, err := ioutil.ReadAll(resp.Body)
	if nil != err {
		panic("post数据读取错误: " + err.Error())
	}
	result = string(resp_data)
	beego.Info("================= Post end =================")
	return
}
